package org.zstacks.znet.ticket;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.zstacks.znet.Message;
 
public class TicketManager { 
	private ConcurrentMap<String, Ticket> tickets = new ConcurrentHashMap<String, Ticket>();
 
	public Ticket getTicket(String id) {
		if(id == null) return null;
		return tickets.get(id);
	}
 
	public Ticket createTicket(Message req, long timeout) {
		return createTicket(req, timeout, null);
	}
 
	public Ticket createTicket(Message req, long timeout, ResultCallback callback) {
		Ticket ticket = new Ticket(req, timeout);
		ticket.setCallback(callback);

		if (tickets.putIfAbsent(ticket.getId(), ticket) != null) {
			throw new IllegalArgumentException("duplicate ticket number.");
		}

		return ticket;
	} 
	
	public Ticket removeTicket(String id) {
		return tickets.remove(id);
	}
	
}
